//日期格式化 
export function formatDate(date, fmt) {
  if (('' + date).length === 0 || !date) {
    return null
  }
  if (('' + date).length === 8) {
    date = formatDateString(date)
  }
  if (typeof date !== 'object') {
    date = new Date(date)
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftzero(str));
    }
  }
  return fmt;
}
//yyyyMMdd转yyyy-MM-dd
export function formatDateString(dateString) {
  var pattern = /(\d{4})(\d{2})(\d{2})/;
  if (dateString.length == 8) {
    var formatedDate = dateString.replace(pattern, '$1-$2-$3');
    return formatedDate;
  } else {
    return dateString;
  }
}
//hhmmss转hh:mm:ss
export function formatTimeString(timeString) {
  var pattern = /(\d{2})(\d{2})(\d{2})/;
  if (timeString.length == 6) {
    var formatedTime = timeString.replace(pattern, '$1:$2:$3');
    return formatedTime;
  } else {
    return timeString;
  }
}
//hh:mm:ss转date
export function timeStringToDate(timeString, dateString = formatDate(new Date, "yyyy-MM-dd")) {
  if (!timeString) {
    return null;
  }
  if (timeString.length === 6) {
    timeString = formatTimeString(timeString)
  }
  var time = dateString + " " + timeString;
  time = time.replace(/-/g, ':').replace(' ', ':');
  time = time.split(':');
  var date = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5]);
  console.log("date",date);
  //var date = new Date(dateString + " " + timeString);
  return date;
}
//日期转date
export function dateStringToDate(dateString) {
  if (!dateString) {
    return null;
  }
  if (dateString.length === 8) {
    dateString = formatDateString(dateString)
  }
  var date = new Date(dateString);
  return date;
}

export function DateDiff(sDate1, sDate2){
  // var aDate, oDate1, oDate2, iDays
  // aDate = sDate1.split("-")
  // oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为9-25-2017格式 
  // console.log(oDate1);
  // aDate = sDate2.split("-")
  // oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  // console.log(oDate2);
  // iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数 
  // console.log(5566);
  // console.log(iDays);
  // return iDays + 1

  var dateSpan,
  iDays;
  sDate1 = Date.parse(sDate1);
  sDate2 = Date.parse(sDate2);
  dateSpan = sDate2 - sDate1;
  dateSpan = Math.abs(dateSpan);
  iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
  return iDays
}


function padLeftzero(str) {
  return ('00' + str).substr(str.length);
};
